import axios from 'axios'

// 简单的消息提示函数
const showMessage = (message, type = 'error') => {
  console.log(`[${type.toUpperCase()}] ${message}`)
  // 这里可以集成任何UI库的消息提示
  // 暂时使用console.log，后续可以替换为Element Plus或其他UI库
}

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 添加token到请求头
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 添加时间戳防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }
    
    return config
  },
  (error) => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { data, status } = response
    
    // 如果响应成功
    if (status === 200) {
      // 根据后端返回的数据结构判断
      if (data.code === 200 || data.code === '200' || data.code === 0) {
        // 对于登录接口返回data字段，对于列表接口返回包含list/total等字段的完整数据
        if (data.list !== undefined || data.total !== undefined) {
          // 列表类型接口，返回包含list、total、page、pageSize的完整数据
          return {
            list: data.list || [],
            total: data.total || 0,
            page: data.page || 1,
            pageSize: data.pageSize || 10
          }
        } else if (data.data !== undefined) {
          // 登录等接口，返回data字段
          return data.data
        } else {
          // 其他接口，返回完整数据
          return data
        }
      } else {
        // 业务错误处理
        const message = data.message || data.msg || '请求失败'
        showMessage(message, 'error')
        return Promise.reject(new Error(message))
      }
    } else {
      showMessage(`请求失败: ${status}`, 'error')
      return Promise.reject(new Error(`请求失败: ${status}`))
    }
  },
  (error) => {
    const { response } = error
    
    if (response) {
      const { status, data } = response
      
      switch (status) {
        case 400:
          showMessage('请求参数错误', 'error')
          break
        case 401:
          showMessage('未授权，请重新登录', 'error')
          // 清除token并跳转到登录页
          localStorage.removeItem('token')
          window.location.href = '/login'
          break
        case 403:
          showMessage('拒绝访问', 'error')
          break
        case 404:
          showMessage('请求的资源不存在', 'error')
          break
        case 500:
          showMessage('服务器内部错误', 'error')
          break
        case 502:
          showMessage('网关错误', 'error')
          break
        case 503:
          showMessage('服务不可用', 'error')
          break
        case 504:
          showMessage('网关超时', 'error')
          break
        default:
          const message = data?.message || data?.msg || '请求失败'
          showMessage(message, 'error')
      }
    } else {
      // 网络错误
      if (error.code === 'ECONNABORTED') {
        showMessage('请求超时，请检查网络连接', 'error')
      } else {
        showMessage('网络错误，请检查网络连接', 'error')
      }
    }
    
    return Promise.reject(error)
  }
)

// 封装request方法
const request = (config) => {
  return new Promise((resolve, reject) => {
    service(config)
      .then(response => {
        resolve(response)
      })
      .catch(error => {
        reject(error)
      })
  })
}

// 封装常用请求方法
request.get = (url, params, config = {}) => {
  return request({
    url,
    method: 'get',
    params,
    ...config
  })
}

request.post = (url, data, config = {}) => {
  return request({
    url,
    method: 'post',
    data,
    ...config
  })
}

request.put = (url, data, config = {}) => {
  return request({
    url,
    method: 'put',
    data,
    ...config
  })
}

request.delete = (url, params, config = {}) => {
  return request({
    url,
    method: 'delete',
    params,
    ...config
  })
}

request.patch = (url, data, config = {}) => {
  return request({
    url,
    method: 'patch',
    data,
    ...config
  })
}

export default request 